import { Food } from '../entities/Food';
import { Vector2D } from '../utils/Vector2D';
import { EnvironmentManager } from './EnvironmentManager';

export class FoodManager {
    private foods: Food[] = [];
    private maxFoods: number = 20;
    private maxMagnetFoods: number = 3;
    private maxPoisonFoods: number = 6;
    private canvas: HTMLCanvasElement; // 新增：保存传递的画布对象
    private environmentManager: EnvironmentManager;
    private snake: Snake | null = null;

    private calculateMaxFoods(): void {
        if (!this.canvas) return;
        
        // 基于画布面积计算最大食物数量
        const canvasArea = this.canvas.width * this.canvas.height;
        const baseArea = 800 * 600; // 基准画布面积
        const baseMaxFoods = 20; // 基准最大食物数量

        // 根据画布面积比例调整最大食物数量
        this.maxFoods = Math.floor(baseMaxFoods * (canvasArea / baseArea));
        // 确保最小和最大限制
        this.maxFoods = Math.max(100, this.maxFoods);

        // 相应调整特殊食物的数量上限
        this.maxMagnetFoods = Math.max(2, Math.floor(this.maxFoods * 0.05));
        this.maxPoisonFoods = Math.max(3, Math.floor(this.maxFoods * 0.15));
    }

    constructor(environmentManager: EnvironmentManager) {
        this.environmentManager = environmentManager;
        // 初始化时不计算食物上限，等待canvas尺寸设置后再计算
    }

    public setSnake(snake: Snake): void {
        this.snake = snake;
    }

    public generateFood(): void {
        if (this.foods.length < this.maxFoods) {
            let position: Vector2D;
            let newFood: Food;
            let isValidPosition = false;

            // 尝试最多10次找到合适的位置
            for (let attempts = 0; attempts < 10; attempts++) {
                position = new Vector2D(
                    Math.random() * (this.canvas.width - 40) + 20, // 使用画布宽度
                    Math.random() * (this.canvas.height - 40) + 20 // 使用画布高度
                );

                // 检查是否与现有食物或蛇身重叠
                let hasOverlap = false;
                
                // 检查与现有食物的重叠
                for (const existingFood of this.foods) {
                    const minDistance = existingFood.getSize() + 25; // 食物之间的最小间距
                    if (position.distance(existingFood.getPosition()) < minDistance) {
                        hasOverlap = true;
                        break;
                    }
                }

                // 检查与蛇身的重叠（不包括蛇头）
                if (!hasOverlap && this.snake) {
                    const segments = this.snake.getSegments();
                    // 从第二个节点开始检查（跳过蛇头）
                    for (let i = 1; i < segments.length; i++) {
                        if (position.distance(segments[i]) < 30) { // 与蛇身的最小间距
                            hasOverlap = true;
                            break;
                        }
                    }
                }

                if (!hasOverlap) {
                    isValidPosition = true;
                    break;
                }
            }

            // 如果找到有效位置，创建新食物
            if (isValidPosition) {
                // 计算当前特殊食物的数量
                const magnetFoodCount = this.foods.filter(food => food.getType() === 'magnet').length;
                const poisonFoodCount = this.foods.filter(food => food.getType() === 'poison').length;

                // 创建新的食物，考虑特殊食物的数量限制
                do {
                    newFood = new Food(position!);
                } while (
                    (newFood.getType() === 'magnet' && magnetFoodCount >= this.maxMagnetFoods) ||
                    (newFood.getType() === 'poison' && poisonFoodCount >= this.maxPoisonFoods)
                );

                this.foods.push(newFood);
            }
        }
    }

    public update(): void {
        // 检查并调整食物位置
        this.checkAndAdjustFoodPositions();

        // 根据画布大小调整食物生成频率
        const canvasArea = this.canvas.width * this.canvas.height;
        const baseArea = 800 * 600;
        const areaFactor = Math.sqrt(canvasArea / baseArea); // 使用平方根来平滑缩放

        // 结合环境因素和画布大小计算生成频率
        const foodSpawnRate = this.environmentManager.getFoodSpawnRate() * 1.5 * areaFactor;

        if (Math.random() < foodSpawnRate) {
            this.generateFood();
            // 额外生成食物的机会，也考虑画布大小
            if (Math.random() < 0.3 * areaFactor) {
                this.generateFood();
            }
        }
    }

    private checkAndAdjustFoodPositions(): void {
        if (!this.snake) return;

        const segments = this.snake.getSegments();
        const minDistance = 30; // 与蛇身的最小安全距离

        for (const food of this.foods) {
            const foodPos = food.getPosition();
            let hasOverlap = false;

            // 检查是否与蛇身重叠（不包括蛇头）
            for (let i = 1; i < segments.length; i++) {
                if (foodPos.distance(segments[i]) < minDistance) {
                    hasOverlap = true;
                    break;
                }
            }

            if (hasOverlap) {
                // 寻找最近的安全位置
                let newPosition = this.findNearestSafePosition(foodPos, segments);
                if (newPosition) {
                    food.setPosition(newPosition);
                }
            }
        }
    }

    private findNearestSafePosition(originalPos: Vector2D, segments: Vector2D[]): Vector2D | null {
        const minDistance = 30; // 与蛇身的最小安全距离
        const searchRadius = 50; // 搜索半径
        const searchSteps = 8; // 搜索方向数量
        const maxAttempts = 5; // 最大尝试次数

        for (let attempt = 1; attempt <= maxAttempts; attempt++) {
            const currentRadius = searchRadius * attempt;

            for (let i = 0; i < searchSteps; i++) {
                const angle = (Math.PI * 2 * i) / searchSteps;
                const testPos = new Vector2D(
                    originalPos.x + Math.cos(angle) * currentRadius,
                    originalPos.y + Math.sin(angle) * currentRadius
                );

                // 确保位置在画布范围内
                if (testPos.x < 20 || testPos.x > this.canvas.width - 20 || // 使用画布宽度
                    testPos.y < 20 || testPos.y > this.canvas.height - 20) { // 使用画布高度
                    continue;
                }

                // 检查是否与蛇身重叠
                let isSafe = true;
                for (const segment of segments) {
                    if (testPos.distance(segment) < minDistance) {
                        isSafe = false;
                        break;
                    }
                }

                // 检查是否与其他食物重叠
                if (isSafe) {
                    for (const food of this.foods) {
                        if (testPos.distance(food.getPosition()) < minDistance) {
                            isSafe = false;
                            break;
                        }
                    }
                }

                if (isSafe) {
                    return testPos;
                }
            }
        }

        return null; // 如果找不到安全位置，返回null
    }

    public removeFood(food: Food): void {
        const index = this.foods.indexOf(food);
        if (index > -1) {
            this.foods.splice(index, 1);
        }
    }

    public reset(): void {
        this.foods = [];
        this.generateFood();
    }

    public getFoods(): Food[] {
        return this.foods;
    }

    public updateCanvasSize(width: number, height: number): void {
        // 创建一个虚拟canvas对象来存储尺寸信息
        this.canvas = {
            width: width,
            height: height
        } as HTMLCanvasElement;
        
        // 更新后重新计算食物上限
        this.calculateMaxFoods();
    }
}